import apiClient from './client'

export interface Conversation {
  id: string
  type: 'DIRECT' | 'GROUP'
  name: string | null
  avatar: string | null
  lastMessage: LastMessage | null
  unreadCount: number
  participants: Participant[]
  createdAt: string
}

export interface LastMessage {
  id: string
  content: string
  senderId: string
  senderName: string | null
  messageType: MessageType
  createdAt: string
}

export interface Participant {
  userId: string
  username: string | null
  avatar: string | null
  role: 'OWNER' | 'ADMIN' | 'MEMBER'
  muted: boolean
  pinned: boolean
}

export interface Message {
  id: string
  conversationId: string
  senderId: string
  senderName: string | null
  senderAvatar: string | null
  messageType: MessageType
  content: string
  metadata: Record<string, any> | null
  replyTo: ReplyMessage | null
  readBy: string[]
  recalled: boolean
  createdAt: string
}

export interface ReplyMessage {
  id: string
  content: string
  senderId: string
  senderName: string | null
}

export type MessageType = 'TEXT' | 'IMAGE' | 'FILE' | 'VOICE' | 'VIDEO' | 'LOCATION' | 'SYSTEM' | 'CARD'

export interface CreateConversationRequest {
  type: 'DIRECT' | 'GROUP'
  participantIds: string[]
  name?: string
  avatar?: string
}

export interface SendMessageRequest {
  conversationId: string
  messageType?: MessageType
  content: string
  metadata?: Record<string, any>
  replyToId?: string
}

export interface MessageListResponse {
  messages: Message[]
  hasMore: boolean
  nextCursor: string | null
}

export const conversationAPI = {
  // 获取会话列表
  getConversations: (): Promise<Conversation[]> => {
    return apiClient.get('/conversations')
  },

  // 创建会话
  createConversation: (data: CreateConversationRequest): Promise<Conversation> => {
    return apiClient.post('/conversations', data)
  },

  // 获取会话详情
  getConversation: (conversationId: string): Promise<Conversation> => {
    return apiClient.get(`/conversations/${conversationId}`)
  },

  // 更新会话
  updateConversation: (conversationId: string, data: { name?: string; avatar?: string }): Promise<Conversation> => {
    return apiClient.put(`/conversations/${conversationId}`, data)
  },

  // 添加成员
  addParticipants: (conversationId: string, userIds: string[]): Promise<Conversation> => {
    return apiClient.post(`/conversations/${conversationId}/participants`, { userIds })
  },

  // 移除成员
  removeParticipant: (conversationId: string, userId: string): Promise<Conversation> => {
    return apiClient.delete(`/conversations/${conversationId}/participants/${userId}`)
  },

  // 退出群聊
  leaveConversation: (conversationId: string): Promise<void> => {
    return apiClient.post(`/conversations/${conversationId}/leave`)
  },

  // 静音/取消静音
  toggleMute: (conversationId: string, muted: boolean): Promise<void> => {
    return apiClient.put(`/conversations/${conversationId}/mute`, null, { params: { muted } })
  },

  // 置顶/取消置顶
  togglePin: (conversationId: string, pinned: boolean): Promise<void> => {
    return apiClient.put(`/conversations/${conversationId}/pin`, null, { params: { pinned } })
  }
}

export const messageAPI = {
  // 发送消息
  sendMessage: (data: SendMessageRequest): Promise<Message> => {
    return apiClient.post('/messages', data)
  },

  // 获取消息列表
  getMessages: (conversationId: string, beforeTime?: string, limit: number = 20): Promise<MessageListResponse> => {
    return apiClient.get(`/messages/conversation/${conversationId}`, {
      params: { beforeTime, limit }
    })
  },

  // 标记消息已读
  markMessagesAsRead: (conversationId: string, messageIds: string[]): Promise<void> => {
    return apiClient.post('/messages/read', { messageIds }, { params: { conversationId } })
  },

  // 标记会话所有消息已读
  markConversationAsRead: (conversationId: string): Promise<void> => {
    return apiClient.post(`/messages/conversation/${conversationId}/read-all`)
  },

  // 撤回消息
  recallMessage: (messageId: string): Promise<Message> => {
    return apiClient.delete(`/messages/${messageId}/recall`)
  },

  // 搜索消息
  searchMessages: (conversationId: string, keyword: string, limit: number = 50): Promise<Message[]> => {
    return apiClient.get('/messages/search', {
      params: { conversationId, keyword, limit }
    })
  },

  // 获取未读数
  getUnreadCount: (conversationId: string): Promise<number> => {
    return apiClient.get(`/messages/conversation/${conversationId}/unread-count`)
  }
}

// AI消息API
export const aiMessageAPI = {
  // 请求会议总结
  requestMeetingSummary: (conversationId: string, startTime: string, endTime: string): Promise<Message> => {
    return apiClient.post('/ai-messages/meeting-summary', null, {
      params: { conversationId, startTime, endTime }
    })
  },

  // 提取任务
  extractTasks: (conversationId: string, messageIds: string[]): Promise<Message[]> => {
    return apiClient.post('/ai-messages/extract-tasks', messageIds, {
      params: { conversationId }
    })
  },

  // 生成内容（商品文案、营销文案等）
  generateContent: (conversationId: string, contentType: string, params: any): Promise<Message> => {
    return apiClient.post('/ai-messages/generate-content', params, {
      params: { conversationId, contentType }
    })
  },

  // 获取销售话术建议
  getSalesScript: (conversationId: string, customerId: string, context: any): Promise<Message> => {
    return apiClient.post('/ai-messages/sales-script', context, {
      params: { conversationId, customerId }
    })
  },

  // 智能语义搜索
  smartSearch: (conversationId: string, query: string, useSemanticSearch: boolean = true): Promise<any[]> => {
    return apiClient.get('/ai-messages/smart-search', {
      params: { conversationId, query, useSemanticSearch }
    })
  },

  // 翻译消息
  translateMessage: (messageId: string, targetLanguage: string): Promise<string> => {
    return apiClient.post('/ai-messages/translate', null, {
      params: { messageId, targetLanguage }
    })
  }
}
